//
//  WebErrorPage.swift
//  NanChangRER
//
//  Created by Groot on 2017/8/26.
//  Copyright © 2017年 Groot. All rights reserved.
//

class ViewLoadingPage: UIView {
    
    var imageView: UIImageView?
    var label: UILabel?
    var refreshHandler: (() -> Void)?
    
    private lazy var tapGestureRecognizer: UITapGestureRecognizer = {
       var tap = UITapGestureRecognizer.init(target: self, action: #selector(refresh))
        tap.isEnabled = false
        return tap
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        initViews()
    }
    
    func error(_ tip: String? = "加载出错了，点击重试", handler: (() -> Void)?) {
        label?.text = tip
        imageView?.image = UIImage.init(named: "sure_placeholder_error")
        if handler != nil {
            tapGestureRecognizer.isEnabled = true
            self.refreshHandler = handler
        }else {
            tapGestureRecognizer.isEnabled = false
        }
    }
    
    func empty(_ tip: String? = "暂无相关内容", handler: (() -> Void)?) {
        label?.text = tip
        imageView?.image = UIImage.init(named: "no_data")
        if handler != nil {
            tapGestureRecognizer.isEnabled = true
            self.refreshHandler = handler
        }else {
            tapGestureRecognizer.isEnabled = false
        }
    }
    
    @objc func refresh() {
        self.refreshHandler?()
        self.removeFromSuperview()
    }
    
    func initViews() {
        isUserInteractionEnabled = true
        addGestureRecognizer(tapGestureRecognizer)
        
        backgroundColor = UIColor.init(white: 0.96, alpha: 1.0)
        
        imageView = UIImageView.init(image: UIImage.init(named: "sure_placeholder_error"))
        addSubview(imageView!)
        imageView?.snp.makeConstraints({ (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-30)
            make.height.width.equalTo(60)
        })
        
        label = UILabel()
        label?.text = "加载出错"
        label?.textColor = UIColor.init(white: 0.5, alpha: 0.8)
        label?.font = UIFont.systemFont(ofSize: 15)
        addSubview(label!)
        label?.snp.makeConstraints({ (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo((imageView?.snp.bottom)!).offset(16)
        })
    }
}
